<template>
  <div>
    <!-- 关键功能：人工标注模式下始终展示叠加画布，直到用户点击完成标注 -->
    <div v-if="annotateMode" class="relative" ref="originalContainer">
      <img :src="originalImage" alt="原始图片" class="w-full h-auto rounded-md shadow-sm">
      <canvas ref="annotCanvas" class="absolute inset-0" @click="onAnnotClick"></canvas>
      <div class="absolute top-2 left-2 bg-black bg-opacity-50 text-white px-2 py-1 rounded text-sm">原图（人工标注）</div>
    </div>

    <!-- 已停用：完成两个区域后在标注模式内切换布局，改为保持叠加画布，等待用户点击“完成标注” -->
    <!-- 已停用：在人工标注模式内因完成两个区域自动切换布局，改为保持叠加画布，等待用户点击“完成标注” -->
    <!--
    <div v-else-if="annotateMode && annotDone" class="grid grid-cols-1 md:grid-cols-2 gap-4">
      <div class="relative">
        <img :src="originalImage" alt="原始图片" class="w-full h-auto rounded-md shadow-sm cursor-pointer hover:opacity-90 transition-opacity" @click="emitPreview(originalImage)">
        <div class="absolute top-2 left-2 bg-black bg-opacity-50 text-white px-2 py-1 rounded text-sm">原图</div>
      </div>
      <div class="relative">
        <img :src="resultImage" alt="检测结果" class="w-full h-auto rounded-md shadow-sm cursor-pointer hover:opacity-90 transition-opacity" @click="emitPreview(resultImage)">
        <div class="absolute top-2 left-2 bg-black bg-opacity-50 text-white px-2 py-1 rounded text-sm">检测结果</div>
      </div>
      <div class="relative" ref="annotPreviewContainer">
        <img :src="originalImage" alt="人工标注结果" class="w-full h-auto rounded-md shadow-sm">
        <canvas ref="annotPreviewCanvas" class="absolute inset-0"></canvas>
        <div class="absolute top-2 left-2 bg-black bg-opacity-50 text-white px-2 py-1 rounded text-sm">人工标注结果</div>
      </div>
    </div>
    
    -->

    <!-- 默认：并排显示原图与检测结果；若存在人工标注结果，则第二排展示预览图 -->
    <div v-else class="grid grid-cols-1 md:grid-cols-2 gap-4">
      <div class="relative" ref="originalContainer">
        <img :src="originalImage" alt="原始图片" class="w-full h-auto rounded-md shadow-sm cursor-pointer hover:opacity-90 transition-opacity" @click="emitPreview(originalImage)">
        <div class="absolute top-2 left-2 bg-black bg-opacity-50 text-white px-2 py-1 rounded text-sm">原图</div>
      </div>
      <div class="relative">
        <img :src="resultImage" alt="检测结果" class="w-full h-auto rounded-md shadow-sm cursor-pointer hover:opacity-90 transition-opacity" @click="emitPreview(resultImage)">
        <div class="absolute top-2 left-2 bg-black bg-opacity-50 text-white px-2 py-1 rounded text-sm">检测结果</div>
      </div>
      <div v-if="annotDone" class="relative" ref="annotPreviewContainer">
        <img :src="originalImage" alt="人工标注结果" class="w-full h-auto rounded-md shadow-sm">
        <canvas ref="annotPreviewCanvas" class="absolute inset-0"></canvas>
        <div class="absolute top-2 left-2 bg-black bg-opacity-50 text-white px-2 py-1 rounded text-sm">人工标注结果</div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch, nextTick, onMounted, onBeforeUnmount } from 'vue'

// 关键功能：输入与输出接口
const props = defineProps({
  originalImage: { type: String, required: true },
  resultImage: { type: String, required: true },
  annotateMode: { type: Boolean, default: false }
})
const emit = defineEmits(['preview', 'manual-update'])

// 关键功能：画布/标注状态
const originalContainer = ref(null)
const annotCanvas = ref(null)
const annotPreviewContainer = ref(null)
const annotPreviewCanvas = ref(null)
const annotCtx = ref(null)
const currentLabel = ref(null) // 'ADENOID' | 'CAVITY'
const currentPoints = ref([])
const polyAdenoid = ref(null)
const polyCavity = ref(null)
const areaAdenoid = ref(0)
const areaCavity = ref(0)
const manualDiagnosis = ref('')
const annotBaseW = ref(0)
const annotBaseH = ref(0)

// 关键功能：标注完成判定
const annotDone = computed(() => {
  const aDone = polyAdenoid.value && Array.isArray(polyAdenoid.value.points) && polyAdenoid.value.points.length >= 3
  const cDone = polyCavity.value && Array.isArray(polyCavity.value.points) && polyCavity.value.points.length >= 3
  return aDone && cDone
})

// 关键功能：按钮状态
const canFinish = computed(() => currentPoints.value.length >= 3)
const canUndo = computed(() => currentPoints.value.length > 0)

// 关键功能：未完成标注检测
function hasIncomplete() {
  return !!(props.annotateMode && currentLabel.value && currentPoints.value && currentPoints.value.length > 0)
}

// 关键功能：预览事件透传
function emitPreview(url) {
  emit('preview', url)
}

// 关键功能：初始化叠加画布
function initAnnotCanvas() {
  const container = originalContainer.value
  const canvas = annotCanvas.value
  if (!container || !canvas) return
  const rect = container.getBoundingClientRect()
  canvas.width = Math.round(rect.width)
  canvas.height = Math.round(rect.height)
  annotCtx.value = canvas.getContext('2d')
  if (!annotBaseW.value || !annotBaseH.value) {
    annotBaseW.value = canvas.width
    annotBaseH.value = canvas.height
  }
  redrawAnnot()
}

function updateAnnotCanvasSize() {
  if (!props.annotateMode) return
  // 关键功能：人工标注状态下仅更新叠加画布尺寸，不初始化预览画布
  initAnnotCanvas()
}

// 关键功能：开始标注区域
function startRegion(label) {
  currentLabel.value = label === 'ADENOID' ? 'ADENOID' : 'CAVITY'
  currentPoints.value = []
  redrawAnnot()
}

// 关键功能：点击添加节点
function onAnnotClick(e) {
  if (!props.annotateMode || !currentLabel.value) return
  const canvas = annotCanvas.value
  if (!canvas) return
  const rect = canvas.getBoundingClientRect()
  const scaleXDisplay = canvas.width / rect.width
  const scaleYDisplay = canvas.height / rect.height
  const xDisplay = (e.clientX - rect.left) * scaleXDisplay
  const yDisplay = (e.clientY - rect.top) * scaleYDisplay
  const toBaseX = annotBaseW.value > 0 ? (annotBaseW.value / canvas.width) : 1
  const toBaseY = annotBaseH.value > 0 ? (annotBaseH.value / canvas.height) : 1
  const x = Math.round(xDisplay * toBaseX)
  const y = Math.round(yDisplay * toBaseY)
  currentPoints.value.push({ x, y })
  redrawAnnot()
}

// 关键功能：撤销节点
function undoPoint() {
  if (currentPoints.value.length === 0) return
  currentPoints.value.pop()
  redrawAnnot()
}

// 关键功能：完成多边形并更新面积与判断
function finishPolygon() {
  if (currentPoints.value.length < 3 || !currentLabel.value) return
  const poly = { points: currentPoints.value.slice() }
  if (currentLabel.value === 'ADENOID') polyAdenoid.value = poly
  else polyCavity.value = poly
  currentPoints.value = []
  currentLabel.value = null
  updateAreasAndDiagnosis()
  redrawAnnot()
  // 关键功能：不在人工标注模式内自动切换到预览，等待父组件“完成标注”确认
}

// 关键功能：查询某区域是否已完成
function isRegionCompleted(label) {
  if (label === 'ADENOID') {
    return !!(polyAdenoid.value && Array.isArray(polyAdenoid.value.points) && polyAdenoid.value.points.length >= 3)
  }
  return !!(polyCavity.value && Array.isArray(polyCavity.value.points) && polyCavity.value.points.length >= 3)
}

// 关键功能：清除指定区域的人工标注
function clearRegion(label) {
  if (label === 'ADENOID') polyAdenoid.value = null
  else polyCavity.value = null
  updateAreasAndDiagnosis()
  redrawAnnot()
  emitManualUpdate()
}

// 关键功能：清除人工标注
function clearManual() {
  currentPoints.value = []
  // currentLabel.value = null
  polyAdenoid.value = null
  polyCavity.value = null
  areaAdenoid.value = 0
  areaCavity.value = 0
  manualDiagnosis.value = ''
  redrawAnnot()
  emitManualUpdate()
}

// 关键功能：绘制当前标注态与已完成区域
function redrawAnnot() {
  const canvas = annotCanvas.value
  const ctx = annotCtx.value
  if (!canvas || !ctx) return
  ctx.clearRect(0, 0, canvas.width, canvas.height)
  const sx = annotBaseW.value > 0 ? (canvas.width / annotBaseW.value) : 1
  const sy = annotBaseH.value > 0 ? (canvas.height / annotBaseH.value) : 1
  if (polyCavity.value && polyCavity.value.points.length >= 3) {
    ctx.save()
    ctx.beginPath()
    const pts = polyCavity.value.points
    ctx.moveTo(pts[0].x * sx, pts[0].y * sy)
    for (let i = 1; i < pts.length; i++) ctx.lineTo(pts[i].x * sx, pts[i].y * sy)
    ctx.closePath()
    ctx.fillStyle = 'rgba(16,185,129,0.35)'
    ctx.strokeStyle = '#10b981'
    ctx.lineWidth = 2
    ctx.fill(); ctx.stroke(); ctx.restore()
  }
  if (polyAdenoid.value && polyAdenoid.value.points.length >= 3) {
    ctx.save()
    ctx.beginPath()
    const pts = polyAdenoid.value.points
    ctx.moveTo(pts[0].x * sx, pts[0].y * sy)
    for (let i = 1; i < pts.length; i++) ctx.lineTo(pts[i].x * sx, pts[i].y * sy)
    ctx.closePath()
    ctx.fillStyle = 'rgba(239,68,68,0.35)'
    ctx.strokeStyle = '#ef4444'
    ctx.lineWidth = 2
    ctx.fill(); ctx.stroke(); ctx.restore()
  }
  if (currentPoints.value.length > 0) {
    ctx.save()
    ctx.strokeStyle = '#3b82f6'
    ctx.lineWidth = 2
    const pts = currentPoints.value
    ctx.beginPath()
    ctx.moveTo(pts[0].x * sx, pts[0].y * sy)
    for (let i = 1; i < pts.length; i++) ctx.lineTo(pts[i].x * sx, pts[i].y * sy)
    ctx.stroke()
    ctx.fillStyle = '#3b82f6'
    for (const p of pts) { ctx.beginPath(); ctx.arc(p.x * sx, p.y * sy, 3, 0, Math.PI * 2); ctx.fill() }
    ctx.restore()
  }
}

// 关键功能：预览画布初始化与绘制（只读）
function initAnnotPreviewCanvas() {
  const container = annotPreviewContainer.value
  const canvas = annotPreviewCanvas.value
  if (!container || !canvas) return
  const rect = container.getBoundingClientRect()
  canvas.width = Math.round(rect.width)
  canvas.height = Math.round(rect.height)
}

function redrawAnnotPreview() {
  const canvas = annotPreviewCanvas.value
  if (!canvas) return
  const ctx = canvas.getContext('2d')
  ctx.clearRect(0, 0, canvas.width, canvas.height)
  const sx = annotBaseW.value > 0 ? (canvas.width / annotBaseW.value) : 1
  const sy = annotBaseH.value > 0 ? (canvas.height / annotBaseH.value) : 1
  if (polyCavity.value && polyCavity.value.points.length >= 3) {
    ctx.save(); ctx.beginPath(); const pts = polyCavity.value.points
    ctx.moveTo(pts[0].x * sx, pts[0].y * sy)
    for (let i = 1; i < pts.length; i++) ctx.lineTo(pts[i].x * sx, pts[i].y * sy)
    ctx.closePath(); ctx.fillStyle = 'rgba(16,185,129,0.35)'; ctx.strokeStyle = '#10b981'; ctx.lineWidth = 2
    ctx.fill(); ctx.stroke(); ctx.restore()
  }
  if (polyAdenoid.value && polyAdenoid.value.points.length >= 3) {
    ctx.save(); ctx.beginPath(); const pts = polyAdenoid.value.points
    ctx.moveTo(pts[0].x * sx, pts[0].y * sy)
    for (let i = 1; i < pts.length; i++) ctx.lineTo(pts[i].x * sx, pts[i].y * sy)
    ctx.closePath(); ctx.fillStyle = 'rgba(239,68,68,0.35)'; ctx.strokeStyle = '#ef4444'; ctx.lineWidth = 2
    ctx.fill(); ctx.stroke(); ctx.restore()
  }
}

// 关键功能：面积计算与诊断
function shoelaceArea(points) {
  let area = 0
  const n = points.length
  for (let i = 0; i < n; i++) {
    const { x: x1, y: y1 } = points[i]
    const { x: x2, y: y2 } = points[(i + 1) % n]
    area += x1 * y2 - x2 * y1
  }
  return Math.abs(area) / 2
}

function updateAreasAndDiagnosis() {
  areaAdenoid.value = polyAdenoid.value ? Math.round(shoelaceArea(polyAdenoid.value.points)) : 0
  areaCavity.value = polyCavity.value ? Math.round(shoelaceArea(polyCavity.value.points)) : 0
  const ratio = areaCavity.value > 0 ? areaAdenoid.value / areaCavity.value : 0
  if (ratio === 0) manualDiagnosis.value = '未完成标注'
  else if (ratio < 0.3) manualDiagnosis.value = '正常'
  else if (ratio < 0.5) manualDiagnosis.value = '轻微堵塞'
  else manualDiagnosis.value = '堵塞严重'
  emitManualUpdate()
}

function emitManualUpdate() {
  emit('manual-update', {
    areaAdenoid: areaAdenoid.value,
    areaCavity: areaCavity.value,
    manualDiagnosis: manualDiagnosis.value,
    annotDone: annotDone.value
  })
}

// 关键功能：监听标注模式切换，初始化/清理事件
watch(() => props.annotateMode, (val) => {
  if (val) {
    nextTick(() => {
      initAnnotCanvas(); window.addEventListener('resize', updateAnnotCanvasSize)
    })
  } else {
    window.removeEventListener('resize', updateAnnotCanvasSize)
    if (annotDone.value) {
      nextTick(() => { initAnnotPreviewCanvas(); redrawAnnotPreview() })
    }
  }
})

onMounted(() => {
  if (props.annotateMode) {
    nextTick(() => { initAnnotCanvas(); window.addEventListener('resize', updateAnnotCanvasSize) })
  }
})

onBeforeUnmount(() => {
  window.removeEventListener('resize', updateAnnotCanvasSize)
})

// 关键功能：对外暴露方法/状态
defineExpose({ startRegion, finishPolygon, undoPoint, clearManual, hasIncomplete, canFinish, canUndo, isRegionCompleted, clearRegion })
</script>

<style scoped>
</style>
